import { useImmer } from "use-immer";
import { initialTravelPlan } from "./Places";
// 定义Place接口，确保与initialTravelPlan结构一致
interface Place {
	id : number;
	title : string;
	childIds : number[];
	// 其他字段可根据实际数据添加
}

type PlacesById = Record<number, Place>;
const TravelPlanImmer = () => {
	const [ plan, updatePlan ] = useImmer( initialTravelPlan ); // 正确使用初始值
	const handleComplete = ( parentId : number, childId : number ) => {
		updatePlan( (draft: PlacesById) => {
			const parent = draft[parentId];
			parent.childIds = parent.childIds.filter( id => id !== childId );
			const deleteAllChildren = ( id : number ) => {
				const place = draft[id];
				place.childIds.forEach( deleteAllChildren );
				delete draft[id];
			};
			deleteAllChildren( childId );
		} );
	}

	const root = plan[0];
	const planetIds = root.childIds;
	return (
		<>
			<h2>Places to visit</h2>
			<ol>
				{planetIds.map(id => (
					<PlaceTree
						key={id}
						id={id}
						parentId={0}
						placesById={plan}
						onComplete={handleComplete}
					/>
				))}
			</ol>
		</>
	);
};

const PlaceTree = ( {
	id,
	placesById,
	onComplete,
	parentId
} : { id : number, placesById : any, onComplete : ( parentId : number, childId : number ) => void, parentId : number } ) => {
	const place = placesById[id];
	const childIds :  number[] = place.childIds;
	return (
		<li >
			{ place.title }
			<button onClick={ () => {
				onComplete( parentId, id );
			} } >
				Complete
			</button >
			{ childIds.length > 0 &&
				<ol >
					{ childIds.map( childId => (
						<PlaceTree
							key={ childId }
							id={ childId }
							parentId={ id }
							placesById={ placesById }
							onComplete={ onComplete }
						/>
					) ) }
				</ol >
			}
		</li >
	);
};

export default TravelPlanImmer;